/*
 * @Author: yangzonglong
 * @Date: 2021-03-08 14:18:55
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: 871387321@qq.com 871387321@qq.com
 * @LastEditTime: 2023-11-10 10:31:55
 * @Auditor: 
 */
import React, { useMemo, useImperativeHandle, forwardRef, useState, useEffect, useCallback } from 'react';
import { Form, Select } from 'antd';
import { SelectProps as AntdSelectProps } from 'antd/lib/select';
import { FormItemProps } from '../../components/components/InputFormItemController';
import useSelectDataSource from './../../hooks/useSelectDataSource';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';

interface NewSelectProps extends AntdSelectProps<any> {
  dataSource?: any[];
  placeholderEn?: string;
  checkbox?: boolean
}

export interface SelectProps extends CanvasItemProps {
  selectProps?: NewSelectProps;
  formItemProps?: FormItemProps;
  disabled?: boolean;
  readOnly?: boolean;
  onChange?: (v?: any) => void;
}

interface StaticSourceRefProps {
  setSource(arr: any[]): void;
  getSource(): any[];
}

const App = (props: SelectProps, ref: React.Ref<StaticSourceRefProps>) => {

  const { disabled, readOnly, formItemProps, selectProps, onChange, domComplete, ...canvasProps } = props;
  const [staticSource, setStaticSource] = useState<any[]>([]);
  const dataSource = useSelectDataSource(selectProps?.dataSource);

  const _disabled = useMemo(() => {
    return readOnly || (typeof disabled === 'boolean' ? disabled : formItemProps?.disabled);
  }, [disabled, formItemProps, readOnly]);
  
  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;
  const placeholder = localStorage.i18nextLng === 'en' ? selectProps?.placeholderEn : selectProps?.placeholder;

  const BridgeSelect = useCallback(({ selectProps, value, onChange, initialValue, }: any) => {
    return (
      <Select 
        allowClear 
        value={_disabled ? value : (value || initialValue)} 
        {...selectProps}
        mode={selectProps.checkbox ? 'tags' : undefined}
        onChange={(e, options: any) => {
          if(Array.isArray(options)) {
            onChange?.({ value: options.map(item => item.value), label: options.map(item => item.children) });
          }else {
            onChange?.(options ? { ...options, label: options.children } : {});
          }
        }}
        placeholder={_disabled ? '' : placeholder}
        disabled={_disabled}>
        {staticSource.map((item: any) => (
          <Select.Option key={item.value} value={item.value}>
            { (localStorage.i18nextLng === 'en' ? item?.labelEn : item.label) || item.label}
          </Select.Option>
        ))}
      </Select>

    );
  }, [_disabled, placeholder, staticSource]);

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  useImperativeHandle(ref, () => ({
    setSource: (source: any[]) => {
      if (source) setStaticSource(source);
    },
    getSource: () => {
      return dataSource;
    }
  }));

  useEffect(() => {
    if (dataSource) {
      setStaticSource(dataSource);
    }
  }, [dataSource]);

  return (
    <Form.Item {...canvasProps} {...formItemProps}
      label={label}
      initialValue={selectProps?.defaultValue} >
      <BridgeSelect
        initialValue={selectProps?.defaultValue}
        selectProps={selectProps}
      />
    </Form.Item>
  );
};

export default forwardRef(App);